﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BLL = FaWorks.WebSite.BussinessLogicLayer;
using Newtonsoft.Json;

namespace FaWorks.WebSite.Controllers
{
    public class UserController : Controller
    {
        public ActionResult AuthLogin()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AuthLogin(FormCollection fc, string returnUrl)
        {
            var userName = fc["UserName"];
            var userPswd = fc["Password"];
            var login = new BLL.Domain.Login();
            if (login.impersonateValidUser(userName, "mysoft.com.cn", userPswd))
            {
                Models.User user = KlDB.Users.FirstOrDefault<Models.User>(m => m.UserName == userName);
                //不存在则添加用户
                if (user == null)
                {
                    user = new Models.User
                        {
                            UserName = userName,
                            Password = userPswd,
                            Email = userName + "@mysoft.com.cn"
                        };
                    KlDB.Users.Add(user);
                    KlDB.SaveChanges();
                }

                //建立身份验证票对象
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName,
                    DateTime.Now, DateTime.Now.AddDays(1),
                    false, JsonConvert.SerializeObject(user), "/"); 
                //加密序列化验证票为字符串 
                string hashTicket = FormsAuthentication.Encrypt(ticket); 
                //生成Cookie 
                HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
                //输出Cookie
                HttpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                HttpContext.Response.Cookies.Add(userCookie);

                return Redirect(string.IsNullOrEmpty(returnUrl) ? "/Knowledge" : returnUrl);
            }

            return Redirect("AuthLogin");
        }

        public ActionResult LoginOut() {
            Models.AjaxResult ar = new Models.AjaxResult();
            HttpContext.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            return Json(ar, JsonRequestBehavior.AllowGet);
        }

        private KlDataBase KlDB = new KlDataBase();
    }
}
